// pages/spell_success/spell_success.js
var common = require("../../../common/common.js").common;

var un = require("../../../siteinfo.js");

var util = require("../../../utils/util.js");

Page({
    /**
   * 页面的初始数据
   */
    data: {
        order_num: "",
        //订单号
        type: "",
        //购买方式
        data: "",
        //数据
        hour: "",
        //时
        minute: "",
        //分
        second: ""
    },
    /**
   * 生命周期函数--监听页面加载
   */
    onLoad: function(options) {
        let that = this;
        that.setData({
            order_num: options.order_num,
            type: options.type,
            domain: app.globalData.domain.slice(0, -10)
        });
        wx.getSystemInfo({
            success: function(res) {
                let rpx = res.windowWidth / 375;
                that.setData({
                    rpx: rpx
                });
            }
        });
        that.getSpell();
    },
    /**
   * 生命周期函数--监听页面初次渲染完成
   */
    onReady: function() {},
    /**
   * 生命周期函数--监听页面显示
   */
    onShow: function() {},
    /**
   * 生命周期函数--监听页面隐藏
   */
    onHide: function() {},
    /**
   * 生命周期函数--监听页面卸载
   */
    onUnload: function() {},
    /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
    onPullDownRefresh: function() {},
    /**
   * 页面上拉触底事件的处理函数
   */
    onReachBottom: function() {},
    /**
   * 用户点击右上角分享
   */
    onShareAppMessage: function() {
        //details.is_one_item == 1
        let that = this;
        let data = that.data.data;
        // console.log(data)
                console.log(data.icon);
        var spellShareImg = that.data.spellShareImg;
        if (data.pro_type == "single") {
            //单规格
            return {
                title: data.pro_name,
                imageUrl: spellShareImg || data.icon,
                path: "/spell/pages/spell_detail/spell_detail?proceed_id=" + data.proceed_id
            };
        } else if (data.pro_type == "multiple") {
            //多规格
            return {
                title: data.pro_name,
                imageUrl: spellShareImg || data.icon,
                path: "/spell/pages/spell_detail/spell_detail?proceed_id=" + data.proceed_id
            };
        }
    },
    //获取拼团信息
    getSpell: function() {
        let that = this;
        let order_num = that.data.order_num;
        common.request({
            endpoint: "Groupbuy/order/show",
            method: "post",
            data: {
                order_num: order_num
            },
            header: {
                "content-type": "application/json"
            },
            success: res => {
                that.setData({
                    data: res.extra
                });
                that.countdown();
                that.getSpellShareImg();
            }
        });
    },
    countdown: function() {
        let that = this;
        let times = that.data.data.remaining_time;
        if (times < 0) {
            times = times + 24 * 3600;
        }
        var timer = null;
        timer = setInterval(function() {
            var day = 0, hour = 0, minute = 0, second = 0;
            //时间默认值
                        if (times > 0) {
                hour = Math.floor(times / (60 * 60)) - day * 24;
                minute = Math.floor(times / 60) - day * 24 * 60 - hour * 60;
                second = Math.floor(times) - day * 24 * 60 * 60 - hour * 60 * 60 - minute * 60;
            }
            if (hour <= 9) hour = "0" + hour;
            if (minute <= 9) minute = "0" + minute;
            if (second <= 9) second = "0" + second;
            that.setData({
                hour: hour,
                minute: minute,
                second: second
            });
            times--;
        }, 1e3);
        if (times <= 0) {
            clearInterval(timer);
        }
    },
    getSpellShareImg_backstage() {
        let that = this;
        var spellData = that.data.data;
        console.log(spellData);
        common.request({
            endpoint: "share/poster_kill",
            method: "post",
            data: {
                list: JSON.stringify(spellData.head_list),
                name: spellData.pro_name,
                price: spellData.low_price,
                original_price: spellData.low_o_price,
                id: spellData.pro_id,
                sku: spellData.sku,
                trade_no: that.data.order_num
            },
            success(res) {
                if (util.compareVersion(un.version, "2.4.20") < 0) {
                    that.setData({
                        spellShareImg: JSON.parse(res).extra.image[0].url
                    });
                } else {
                    that.setData({
                        spellShareImg: res.extra.url
                    });
                }
            }
        });
    },
    //获取分享图
    getSpellShareImg: function() {
        let that = this;
        var spellData = that.data.data;
        const ctx = wx.createCanvasContext("shareCanvas");
        let icon = spellData.icon;
        if (icon.indexOf("https:") < 0) {
            icon = icon.replace("http:", "https:");
        }
        ctx.setFillStyle("#FFF6F5");
        ctx.fillRect(0 * that.data.rpx, 0 * that.data.rpx, 300 * that.data.rpx, 240 * that.data.rpx);
        ctx.drawImage(that.data.domain + "/img/mainPack/spell_share_img.png", 0 * that.data.rpx, 2.5 * that.data.rpx, 300 * that.data.rpx, 37 * that.data.rpx);
        let times = spellData.remaining_time * 1e3 + new Date().getTime();
        var nextDate = new Date(times);
        var year = nextDate.getFullYear();
        var month = nextDate.getMonth() + 1;
        var day = nextDate.getDate();
        var hour = nextDate.getHours();
        var minutes = nextDate.getMinutes();
        var second = nextDate.getSeconds();
        if (month <= 9) month = "0" + month;
        if (day <= 9) day = "0" + day;
        if (minutes <= 9) minutes = "0" + minutes;
        if (second <= 9) second = "0" + second;
        var time1 = year + "-" + month + "-" + day + " " + hour + ":" + minutes + ":" + second;
        console.log("time1" + time1);
        ctx.fillStyle = "#F33D32";
        ctx.font = "normal bold 12px YaHei";
        ctx.fillText("失效时间：" + time1, 75 * that.data.rpx, 46 * that.data.rpx);
        ctx.setLineWidth = 2 * that.data.rpx;
        ctx.setStrokeStyle("#FFA096");
        ctx.strokeRect(13 * that.data.rpx, 54 * that.data.rpx, 274 * that.data.rpx, 176 * that.data.rpx);
        wx.getImageInfo({
            src: icon,
            success: function(res) {
                ctx.drawImage(res.path, 28 * that.data.rpx, 70 * that.data.rpx, 114 * that.data.rpx, 114 * that.data.rpx);
                that.dealWords({
                    ctx: ctx,
                    font: "normal bold 13px YaHei",
                    FillStyle: "#666",
                    word: spellData.pro_name,
                    maxWidth: 106 * that.data.rpx,
                    x: 151.5 * that.data.rpx,
                    y: 68 * that.data.rpx,
                    maxLine: 2
                });
                // that.strokeRoundRect(ctx, 154 * that.data.rpx, 104.5 * that.data.rpx, 34 * that.data.rpx, 15 * that.data.rpx, 3 * that.data.rpx, 1 * that.data.rpx, '#F33D32');
                                ctx.fillStyle = "#F33D32";
                ctx.font = "10px YaHei";
                ctx.fillText(spellData.head_list.length + "人团", 158 * that.data.rpx, 116 * that.data.rpx);
                ctx.fillStyle = "#F33D32";
                ctx.font = "normal bold 18px YaHei";
                ctx.fillText("￥" + spellData.low_price.toFixed(2), 154 * that.data.rpx, 142 * that.data.rpx);
                ctx.fillStyle = "#ccc";
                ctx.font = "10px YaHei";
                ctx.fillText("￥" + spellData.low_o_price.toFixed(2), 154 * that.data.rpx, 154 * that.data.rpx);
                var low_oprice_width = ctx.measureText("￥" + spellData.low_o_price.toFixed(2)).width;
                ctx.strokeStyle = "#ccc";
                ctx.setLineWidth = 2 * that.data.rpx;
                ctx.moveTo(154 * that.data.rpx, 150 * that.data.rpx);
                ctx.lineTo((154 + low_oprice_width) * that.data.rpx, 150 * that.data.rpx);
                ctx.setFillStyle("#F33D32");
                ctx.fillRect(201 * that.data.rpx, 154 * that.data.rpx, 72 * that.data.rpx, 27 * that.data.rpx);
                ctx.fillStyle = "#fff";
                ctx.font = "12px YaHei";
                ctx.fillText("立即拼团", 215 * that.data.rpx, 172 * that.data.rpx);
                ctx.stroke();
                var head_list = spellData.head_list.filter(x => {
                    return x.img != "?";
                });
                for (let i = 0; i < head_list.length; i++) {
                    let k = i;
                    console.log("k" + k);
                    wx.getImageInfo({
                        src: head_list[k].img,
                        success(res) {
                            ctx.save();
                            ctx.beginPath();
                            //开始绘
                                                        ctx.arc(40 * that.data.rpx + 32 * k * that.data.rpx, 206 * that.data.rpx, 12 * that.data.rpx, 0, 2 * Math.PI);
                            ctx.setFillStyle("#fff");
                            ctx.clip();
                            ctx.drawImage(res.path, 28 * that.data.rpx + 32 * k * that.data.rpx, 194 * that.data.rpx, 24 * that.data.rpx, 24 * that.data.rpx);
                            ctx.restore();
                            // that.strokeRoundRect(ctx,31*that.data.rpx,213*that.data.rpx,18*that.data.rpx,10*that.data.rpx,5*that.data.rpx,2*that.data.rpx,'#FF7B19');
                                                        ctx.setFillStyle("#FF7B19");
                            ctx.fillRect(31 * that.data.rpx + 32 * k * that.data.rpx, 213 * that.data.rpx, 18 * that.data.rpx, 10 * that.data.rpx);
                            that.strokeRoundRect(ctx, 31 * that.data.rpx + 32 * k * that.data.rpx, 213 * that.data.rpx, 18 * that.data.rpx, 10 * that.data.rpx, 5 * that.data.rpx, 2 * that.data.rpx, "#FF7B19");
                            ctx.fillStyle = "#fff";
                            ctx.font = "6px YaHei";
                            ctx.fillText("拼主", 34 * that.data.rpx + 32 * k * that.data.rpx, 220 * that.data.rpx);
                            if (k == head_list.length - 1) {
                                var no_head_list = spellData.head_list.filter(x => {
                                    return x.img == "?";
                                });
                                if (no_head_list.length) {
                                    for (let j = 0; j < no_head_list.length; j++) {
                                        var n = j;
                                        ctx.save();
                                        ctx.beginPath();
                                        ctx.arc(40 * that.data.rpx + 32 * (n + 1) * that.data.rpx, 206 * that.data.rpx, 12 * that.data.rpx, 0, 2 * Math.PI);
                                        ctx.stroke();
                                        ctx.fillStyle = "#B0B0B0";
                                        ctx.font = "14px YaHei";
                                        ctx.fillText("?", 36 * that.data.rpx + 32 * (n + 1) * that.data.rpx, 212 * that.data.rpx);
                                        if (j == no_head_list.length - 1) {
                                            ctx.draw(true, () => {
                                                wx.canvasToTempFilePath({
                                                    canvasId: "shareCanvas",
                                                    fileType: "png",
                                                    success: function(res) {
                                                        that.setData({
                                                            spellShareImg: res.tempFilePath
                                                        });
                                                    },
                                                    fail: function(res) {},
                                                    complete: function(res) {}
                                                }, that);
                                            });
                                        }
                                    }
                                } else {
                                    ctx.draw(true, () => {
                                        wx.canvasToTempFilePath({
                                            canvasId: "shareCanvas",
                                            fileType: "png",
                                            success: function(res) {
                                                that.setData({
                                                    spellShareImg: res.tempFilePath
                                                });
                                            },
                                            fail: function(res) {},
                                            complete: function(res) {}
                                        }, that);
                                    });
                                }
                            }
                        }
                    });
                }
            }
        });
    },
    //处理文字多出省略号显示
    dealWords: function(options) {
        options.ctx.setFontSize(options.fontSize);
        //设置字体大小
                options.ctx.font = options.font;
        options.ctx.setFillStyle(options.FillStyle);
        //设置字体颜色
                var allRow = Math.ceil(options.ctx.measureText(options.word).width / options.maxWidth);
        //实际总共能分多少行
                var count = allRow >= options.maxLine ? options.maxLine : allRow;
        //实际能分多少行与设置的最大显示行数比，谁小就用谁做循环次数
                var endPos = 0;
        //当前字符串的截断点
                for (var j = 0; j < count; j++) {
            var nowStr = options.word.slice(endPos);
            //当前剩余的字符串
                        var rowWid = 0;
            //每一行当前宽度    
                        if (options.ctx.measureText(nowStr).width > options.maxWidth) {
                //如果当前的字符串宽度大于最大宽度，然后开始截取
                for (var m = 0; m < nowStr.length; m++) {
                    rowWid += options.ctx.measureText(nowStr[m]).width;
                    //当前字符串总宽度
                                        if (rowWid > options.maxWidth) {
                        if (j === options.maxLine - 1) {
                            //如果是最后一行
                            options.ctx.fillText(nowStr.slice(0, m - 1) + "...", options.x, options.y + (j + 1) * 18);
                            //(j+1)*18这是每一行的高度        
                                                } else {
                            options.ctx.fillText(nowStr.slice(0, m), options.x, options.y + (j + 1) * 18);
                        }
                        endPos += m;
                        //下次截断点
                                                break;
                    }
                }
            } else {
                //如果当前的字符串宽度小于最大宽度就直接输出
                options.ctx.fillText(nowStr.slice(0), options.x, options.y + (j + 1) * 18);
            }
        }
    },
    /**该方法用来绘制圆角矩形 
   *@param cxt:canvas的上下文环境 
   *@param x:左上角x轴坐标 
   *@param y:左上角y轴坐标 
   *@param width:矩形的宽度 
   *@param height:矩形的高度 
   *@param radius:圆的半径 
   *@param lineWidth:线条粗细 
   *@param strokeColor:线条颜色 
   **/
    strokeRoundRect(cxt, x, y, width, height, radius, /*optional*/ lineWidth, /*optional*/ strokeColor) {
        //圆的直径必然要小于矩形的宽高 
        if (2 * radius > width || 2 * radius > height) {
            return false;
        }
        cxt.save();
        cxt.translate(x, y);
        //绘制圆角矩形的各个边 
                this.drawRoundRectPath(cxt, width, height, radius);
        cxt.lineWidth = lineWidth || 2;
        //若是给定了值就用给定的值否则给予默认值2 
                cxt.strokeStyle = strokeColor || "#000";
        cxt.stroke();
        cxt.restore();
    },
    drawRoundRectPath(cxt, width, height, radius) {
        cxt.beginPath(0);
        //从右下角顺时针绘制，弧度从0到1/2PI  
                cxt.arc(width - radius, height - radius, radius, 0, Math.PI / 2);
        //矩形下边线  
                cxt.lineTo(radius, height);
        //左下角圆弧，弧度从1/2PI到PI  
                cxt.arc(radius, height - radius, radius, Math.PI / 2, Math.PI);
        //矩形左边线  
                cxt.lineTo(0, radius);
        //左上角圆弧，弧度从PI到3/2PI  
                cxt.arc(radius, radius, radius, Math.PI, Math.PI * 3 / 2);
        //上边线  
                cxt.lineTo(width - radius, 0);
        //右上角圆弧  
                cxt.arc(width - radius, radius, radius, Math.PI * 3 / 2, Math.PI * 2);
        //右边线  
                cxt.lineTo(width, height - radius);
        cxt.closePath();
    }
});